package com.etcn.common.payment.wxpay.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * 微信支付工具类
 * @author guozc
 * @date 2016-02-18
 */
public class WxPayUtil {

	/**
	 * map转成 <xml> <appid>wx2421b1c4370ec43b</appid> <attach>支付测试</attach>
	 * <body>JSAPI支付测试</body> <mch_id>10000100</mch_id>
	 * <nonce_str>1add1a30ac87aa2db72f57a2375d8fec</nonce_str>
	 * <notify_url>http://wxpay.weixin.qq.com/pub_v2/pay/notify.v2.php
	 * </notify_url> <openid>oUpF8uMuAJO_M2pxb1Q9zNjWeS6o</openid>
	 * <out_trade_no>1415659990</out_trade_no>
	 * <spbill_create_ip>14.23.150.211</spbill_create_ip>
	 * <total_fee>1</total_fee> <trade_type>JSAPI</trade_type>
	 * <sign>0CB01533B8C1EF103065174F50BCA001</sign> </xml> 格式字符串
	 * 
	 * @param map
	 * @return
	 */
	public static String mapToXml(Map<String, Object> map) {
		StringBuffer xml = new StringBuffer();
		List<String> keys = new ArrayList<String>(map.keySet());
		xml.append("<xml>");
		for (String key : keys) {
			xml.append("<");
			xml.append(key);
			xml.append(">");
			xml.append(map.get(key));
			xml.append("</");
			xml.append(key);
			xml.append(">");
		}
		xml.append("</xml>");
		return xml.toString();
	}
	
	/**
	 * xml字符串装map类型
	 * @param xmlString xml字符串
	 * @return map
	 * @throws Exception
	 */
	public static Map<String,Object> xmlToMap(String xmlString) throws Exception{
		if(StringUtils.isEmpty(xmlString)) {  
            return null;  
        }  
        Map<String, Object> map = new HashMap<String, Object>();  
        //将xml格式的字符串转换成Document对象  
        Document doc = DocumentHelper.parseText(xmlString);  
        //获取根节点  
        Element root = doc.getRootElement();  
        //获取根节点下的所有元素  
        List<Element> children = root.elements();  
        //循环所有子元素  
        if(children != null && children.size() > 0) {  
            for(int i = 0; i < children.size(); i++) {  
                Element child = (Element)children.get(i);  
                map.put(child.getName(), child.getTextTrim());  
            }  
        }  
        return map; 
    }

}
